<template>
  <div class="we-chart-login">
    <div class="login-auth-text">
      <span v-if="!hasError">微信授权登陆中...</span>
      <span v-else>微信授权登陆失败</span>
    </div>
  </div>
</template>

<script>
  import {
    mapActions
  } from 'vuex';
  import Storage from 'storage';
  import WeChartApi from 'services/weChartApi';

  export default {
    data() {
      return {
        hasError: false,
        code:null
      };
    },

    created() {
      let code = this.$route.query.code;
      if (code === undefined) {
        return;
      }
      this.code = code;
      this.authLogin();
    },

    methods: {
      authLogin() {
        WeChartApi.authLogin(this.code).then(res => {
          let user = res.user;
          Storage.setSession('user',user)

          this.setAuthToken(res.authToken);
          this.setRefreshToken({
            data: res.refreshToken,
            time: this.$moment().valueOf()
          });

          this.hasError = false;
          this.$router.replace({
            path: '/bindAccount'
          });
        }).catch(() => {
          this.hasError = true;
        });
      },

      ...mapActions(['setAuthToken', 'setRefreshToken'])
    }
  };

</script>

<style lang="scss" scoped>
  .we-chart-login {
    height: 100%;
    position: relative;
    font-size: 16px;

    .login-auth-text {
      @extend .center-middle;
    }
  }

</style>
